import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:smart_translator/app/style/widget_style.dart';
import 'package:smart_translator/app/widgets/CommonWidgets.dart';
import '../../../event/DataCallBack.dart';
import '../../../nets/NetWorkManager.dart';
import '../../../routes/app_pages.dart';
import '../../../services/AudioService.dart';
import '../../../style/app_colors.dart';
import '../../../widgets/AppHeader.dart';
import '../../realTranslation/controllers/real_translation_controller.dart';
import '../controllers/real_time_landscape_controller.dart';

class RealTimeLandscapeView extends GetView<RealTimeLandscapeController> {
  const RealTimeLandscapeView({super.key});
  @override
  Widget build(BuildContext context) {
    return RealTranslationViewStateful(controller);
  }
}

class RealTranslationViewStateful extends StatefulWidget {

  RealTimeLandscapeController realTimeLandscapeController;
  RealTranslationViewStateful(this.realTimeLandscapeController, {super.key});

  @override
  State<StatefulWidget> createState() {
    return RealTranslateViewState();
  }


}

class RealTranslateViewState extends State<RealTranslationViewStateful>  with SingleTickerProviderStateMixin {

  AnimationController?  animationController;
  late Animation<double> rotation;

  bool hasRotated = false;

  final ScrollController fromController = ScrollController();
  final ScrollController toController = ScrollController();

  final screenSize = MediaQuery.of(Get.context!).size;
  double screenWidth = 0.0;
  double screenHeight = 0.0;


  RealTranslationController? realTranslationController;
  AudioService audioService = Get.find<AudioService>();

  // 防抖计时器
  Timer? _debounceTimer;
  // 是否处于冷却状态
  bool _isCoolingDown = false;

  @override
  void initState() {
    super.initState();
    realTranslationController = Get.put(RealTranslationController());

    animationController = AnimationController(
      vsync: this, // 直接传递 State 自身作为 TickerProvider
      duration: Duration(seconds: 2),
    );

    rotation = Tween<double>(begin: 0, end: 0.5)
        .animate(CurvedAnimation(
      parent: animationController!,
      curve: Curves.easeInOut,
    ));
  }





  void fromScrollToBottom() {
    if (fromController.hasClients) {
      Future.delayed(Duration(milliseconds: 500),() {
        fromController.animateTo(
          fromController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      });
    }
  }

  void toScrollToBottom() {
    if (toController.hasClients) {
      toController.animateTo(
        toController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
          children: [
            Container(
              child: InkWell(
                onTap: (){
                 showPoupWindow(context);
                },
                child: SvgPicture.asset(
                  "assets/images/header_part_bg.svg",
                  width: widget.realTimeLandscapeController.screenHeight,
                  fit: BoxFit.fitWidth,
                ),
              ),
            ),
            AppHeader.obtainHeaderForRealTranslationForLandscape(widget.realTimeLandscapeController.screenWidth,
                widget.realTimeLandscapeController.screenHeight),
            Obx(()=> Container(
              width: widget.realTimeLandscapeController.screenHeight,
              margin: EdgeInsets.only(top: 30.w),
              padding: EdgeInsets.all(20.h),
              child: Column(
                children: [
                  Expanded(child:  RotationTransition(
                    turns: rotation,
                    child:  InkWell(
                      onTap: () {
                        showPoupWindow(context);
                      },
                      child: Container(
                        width: widget.realTimeLandscapeController.screenHeight,
                        decoration: BoxDecoration(
                          boxShadow: [
                            CommonWidgets.getBoxShadow(),
                          ],
                          color:  Colors.white,
                          borderRadius: BorderRadius.only(topLeft: Radius.circular(8),topRight: Radius.circular(8)), // Optional: add border radius
                        ),
                        child: Stack(
                          children: [
                            audioService.finalToLanguage.value == '' ? Container(
                              width: widget.realTimeLandscapeController.screenHeight,
                              child: Center(
                                child: Column(
                                  children: [
                                    SizedBox(height: 10.w,),
                                    Image.asset('assets/images/empty_list_realtime.png',width: 169.h,height: 91.w),
                                    Text('点击下方开始键开始同声翻译',style: AppStyleThemeData.HINT_TEXT_STYLE_small,)

                                  ],
                                ),
                              ),
                            ): Container(
                              width: widget.realTimeLandscapeController.screenHeight,
                              padding: EdgeInsets.only(top:40.h,left: 20.w,right: 20.w),
                              child: SingleChildScrollView(
                                controller: toController,
                                child: SingleChildScrollView(
                                  child: Text(audioService.finalToLanguage.value,style: TextStyle(
                                      color: AppColors.hint_text_color.withValues(alpha: 0.4),
                                      fontSize: realTranslationController!.fontSize.value.sp
                                  )),
                                ),
                              ),
                            ),
                            Positioned(
                              child: Text('${audioService.toLanFlagDisplay.value}',style: AppStyleThemeData.HINT_TEXT_STYLE),
                              left: 15.w,
                              top: 15.h,
                            )
                          ],
                        ),
                      ),
                    ),
                  ),),
                  Container(
                    width: widget.realTimeLandscapeController.screenHeight,
                    decoration: BoxDecoration(
                        boxShadow: [
                          CommonWidgets.getBoxShadow(),
                        ],
                        color:  Colors.white // Optional: add border radius
                    ),//声波纹.
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Container(
                              child: InkWell(
                                onTap: () {
                                  if (!hasRotated) {
                                    animationController!.forward();
                                    hasRotated = true;
                                  } else {
                                    animationController!.reset();
                                    hasRotated = false;
                                  }

                                },
                                child: Container(
                                  padding: EdgeInsets.only(left: 10.w,right: 10.w,),
                                  child: Image.asset('assets/images/icon_realtime_roate.png',width: 20.w,height: 20.h),
                                ),
                              ),
                            ),
                            SizedBox(width: 20.w,)
                          ],
                        ),
                        Row(
                          children: [
                            Image.asset('assets/images/icon_video_wave_sideline.png',width: 13.w,height: 13.h,),
                            Expanded(child: CommonWidgets.getMyDivider()),
                            Image.asset('assets/images/icon_audio_wave_realtime.png',width: 176.w,height: 24.h),
                            Expanded(child: CommonWidgets.getMyDivider()),
                            Image.asset('assets/images/icon_video_wave_sideline.png',width: 13.w,height: 13.h,),

                          ],
                        )

                      ],
                    ),
                  ),
                  Expanded(child: InkWell(
                    onTap: () {
                      showPoupWindow(context);
                    },
                    child:  Container(
                      width: widget.realTimeLandscapeController.screenHeight,
                      decoration: BoxDecoration(
                        boxShadow: [
                          CommonWidgets.getBoxShadow(),
                        ],
                        color:  Colors.white,
                        borderRadius: BorderRadius.only(bottomLeft: Radius.circular(8),bottomRight: Radius.circular(8)), // Optional: add border radius
                      ),
                      child: Stack(
                        children: [
                          audioService.finalFromLanguage.value == ''? Container(
                            width: widget.realTimeLandscapeController.screenHeight,
                            child: Center(
                              child: Column(
                                children: [
                                  Image.asset('assets/images/empty_list_realtime.png',width: 169.h,height: 91.w),
                                  SizedBox(height: 16.w,),
                                  Text('点击下方开始键开始同声翻译',style: AppStyleThemeData.HINT_TEXT_STYLE_small,)

                                ],
                              ),
                            ),
                          ): Container(
                            width: widget.realTimeLandscapeController.screenHeight,
                            padding: EdgeInsets.only(top:40.h,left: 20.w,right: 20.w),
                            child: SingleChildScrollView(
                              controller: fromController,
                              child: Text(audioService.finalFromLanguage.value,style: TextStyle(
                                  color: AppColors.hint_text_color.withValues(alpha: 0.4),
                                  fontSize: realTranslationController!.fontSize.value.sp
                              )),
                            ),
                          ),
                          Positioned(
                            child: Text('${audioService.fromLanFlagDisplay.value}',style: AppStyleThemeData.HINT_TEXT_STYLE),
                            left: 15.w,
                            top: 15.h,
                          )

                        ],
                      ),
                    ),
                  )),

                ],
              ),
            ))

          ],
        )
    );
  }

  @override
  void deactivate() {
    super.deactivate();
    _debounceTimer?.cancel(); // 组件销毁时取消计时器
  }

  void showPoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => StatefulBuilder(
          builder: (context, setState) {
            return Obx(()=> SafeArea(child: Container(
              height: 85.h,
              padding: EdgeInsets.all(15.h),
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children: [
                    InkWell(
                      onTap: () {
                        if (_isCoolingDown) {
                          return;
                        };

                        _isCoolingDown = true;

                        if (!audioService.isPlaying.value) {
                          audioService.record();
                        } else {
                          audioService.pauseRecorder();
                        }

                        _debounceTimer = Timer(Duration(milliseconds: 800), () {
                          _isCoolingDown = false;
                        });
                      },
                      child: Container(
                        child: audioService.isPlaying.value ? Image.asset('assets/images/icon_play_realtime_btn_running.png',width: 55.w,height: 55.h):
                        Image.asset('assets/images/icon_play_realtime_btn.png',width: 55.w,height: 55.h),
                      ),
                    ),
                    SizedBox(width: 20.w,),
                    InkWell(
                      onTap: () {
                        Get.back();
                        showFontPoupWindow(context);
                      },
                      child: SingleChildScrollView(
                        child: Container(
                          padding: EdgeInsets.all(8.w),
                          decoration: BoxDecoration(
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black.withValues(alpha: 0.1),
                                spreadRadius: 2.w,
                                blurRadius: 7.w,
                                offset: Offset(0, 8.sp), // changes position of shadow
                              ),
                            ],
                            color:  Colors.white,
                            borderRadius: BorderRadius.circular(8), // Optional: add border radius
                          ),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text('${realTranslationController!.fontSizeShow.value}',style: AppStyleThemeData.normal_bold_small,),
                              Text('字体大小',style: AppStyleThemeData.normal_bold_small,)
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 20.w,),
                    // 字幕共享功能暂时注释，添加一个 SizedBox(width: 70.w,)填充，后续开放字幕共享SizedBox(width: 70.w,)记得删去
                    SizedBox(width: 70.w,),
                    // Container(
                    //   padding: EdgeInsets.all(8.w),
                    //   decoration: BoxDecoration(
                    //     boxShadow: [
                    //       BoxShadow(
                    //         color: Colors.black.withValues(alpha: 0.1),
                    //         spreadRadius: 2.w,
                    //         blurRadius: 7.w,
                    //         offset: Offset(0, 8.sp), // changes position of shadow
                    //       ),
                    //     ],
                    //     color:  Colors.white,
                    //     borderRadius: BorderRadius.circular(8), // Optional: add border radius
                    //   ),
                    //   child: Column(
                    //     mainAxisSize: MainAxisSize.min,
                    //     children: [
                    //       Image.asset('assets/images/icon_screen_share_realtime.png',width: 16.w,height: 16.h),
                    //       Text('字幕共享',style: AppStyleThemeData.normal_bold_small,)
                    //     ],
                    //   ),
                    // ),
                    SizedBox(width: 20.w,),
                    InkWell(
                      onTap: () {
                        showLanguagePoupWindow(context);
                      },
                      child: Container(
                        padding: EdgeInsets.only(top:8.h,bottom:8.h,left: 17.w,right: 27.w),
                        decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.1),
                              spreadRadius: 2.w,
                              blurRadius: 7.w,
                              offset: Offset(0, 8.sp), // changes position of shadow
                            ),
                          ],
                          color:  Colors.white,
                          borderRadius: BorderRadius.circular(8), // Optional: add border radius
                        ),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text('${audioService.fromLanFlagDisplay.value.substring(0,1) + '-' +
                                audioService.toLanFlagDisplay.value.substring(0,1)}',style: AppStyleThemeData.normal_bold_small,),
                            Text('语言设置',style: AppStyleThemeData.normal_bold_small,)
                          ],
                        ),
                      ),
                    )
                  ],
                ),
              ),
            )));
          },
        ),
        backgroundColor: Colors.white.withValues(alpha: 0.5),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(
            top: Radius.zero, // 顶部直角
          ),
        ),
        barrierColor: Colors.black.withValues(alpha: 0.1)
    );
  }


  void showFontPoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SafeArea(child: Container(
          height: 280.h,
          padding: EdgeInsets.all(15.h),
          child: SingleChildScrollView(
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('字体大小', style: AppStyleThemeData.HINT_TEXT_STYLE,),
                    InkWell(
                      onTap: () {
                        Get.back();
                      },
                      child: Image.asset('assets/images/icon_poup_window_close.png',width: 10.w,height: 10.h),
                    )

                  ],
                ),
                SizedBox(height: 15.h,),
                CommonWidgets.getMyDivider(),
                SizedBox(height: 15.h,),
                InkWell(
                  onTap: () {
                    setState(() {
                      realTranslationController!.fontSize.value = 32;
                      realTranslationController!.fontSizeShow.value = '32 (偏大)';
                    });
                    Get.back();
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('32 (偏大)',style: AppStyleThemeData.linkStyle_BIG,),
                    ],
                  ),
                ),
                SizedBox(height: 15.h,),
                CommonWidgets.getMyDivider(),
                SizedBox(height: 15.h,),
                InkWell(
                  onTap: (){
                    setState(() {
                      realTranslationController!.fontSizeShow.value = '24 (大)';
                      realTranslationController!.fontSize.value = 24;
                    });
                    Get.back();
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('24 (大)',style: AppStyleThemeData.linkStyle_BIG,),
                    ],
                  ),
                ),
                SizedBox(height: 15.h,),
                CommonWidgets.getMyDivider(),
                SizedBox(height: 15.h,),
                InkWell(
                  onTap: () {
                    setState(() {
                      realTranslationController!.fontSizeShow.value = '18 (适中)';
                      realTranslationController!.fontSize.value = 18;
                    });
                    Get.back();
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('18 (适中)',style: AppStyleThemeData.linkStyle_BIG,),
                    ],
                  ),
                ),
                SizedBox(height: 15.h,),
                CommonWidgets.getMyDivider(),
                SizedBox(height: 15.h,),
                InkWell(
                  onTap: () {
                    setState(() {
                      realTranslationController!.fontSizeShow.value = '16 (小)';
                      realTranslationController!.fontSize.value = 16;
                    });
                    Get.back();
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('16 (小)',style: AppStyleThemeData.linkStyle_BIG,),
                    ],
                  ),
                ),
              ],
            ),
          ),
        )),
        backgroundColor: Colors.white
    );
  }


  void showLanguagePoupWindow(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => StatefulBuilder(builder: (context,setState) {
          return Obx(()=> SafeArea(child: Container(
            padding: EdgeInsets.all(15.h),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('语言设置', style: AppStyleThemeData.HINT_TEXT_STYLE,),
                    InkWell(
                      onTap: () {
                        Get.back();
                      },
                      child: Image.asset('assets/images/icon_poup_window_close.png',width: 10.w,height: 10.h),
                    )

                  ],
                ),
                SizedBox(height: 15.h,),
                CommonWidgets.getMyDivider(),
                SizedBox(height: 15.h,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    InkWell(
                      onTap: () {
                        chooseToLanguages(setState);
                      },
                      child: Container(
                        width: 96.w,
                        padding: EdgeInsets.all(8.w),
                        decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withValues(alpha: 0.1),
                              spreadRadius: 2.w,
                              blurRadius: 7.w,
                              offset: Offset(0, 8.sp), // changes position of shadow
                            ),
                          ],
                          color:Colors.white,
                          borderRadius: BorderRadius.circular(8), // Optional: add border radius
                        ),
                        child: Text('${audioService.fromLanFlagDisplay.value}',style: AppStyleThemeData.normal_bold,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ),

                    Container(
                      padding: EdgeInsets.all(14.w),
                      decoration: BoxDecoration(
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            spreadRadius: 2.w,
                            blurRadius: 7.w,
                            offset: Offset(0, 8.sp), // changes position of shadow
                          ),
                        ],
                        color:Colors.white,
                        borderRadius: BorderRadius.circular(8), // Optional: add border radius
                      ),
                      child: Image.asset('assets/images/icon_index_lang_exchange.png',width: 20.w,height: 20.h,),
                    ),
                    InkWell(
                      onTap: () {
                        chooseToLanguages(setState);
                      },
                      child: Container(
                        width: 96.w,
                        padding: EdgeInsets.all(8.w),
                        decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.1),
                              spreadRadius: 2.w,
                              blurRadius: 7.w,
                              offset: Offset(0, 8.sp), // changes position of shadow
                            ),
                          ],
                          color:Colors.white,
                          borderRadius: BorderRadius.circular(8), // Optional: add border radius
                        ),
                        child: Text('${audioService.toLanFlagDisplay.value}',style: AppStyleThemeData.normal_bold,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    )
                  ],
                ),
                SizedBox(height: 15.h,),
                Container(
                  width: Get.width,
                  child: ElevatedButton(onPressed: () {
                    changeLanguageReInitial();
                    Get.back();
                  }, child: Text('确定')),
                ),
              ],
            ),
          )));
        }),
        backgroundColor: Colors.white
    );
  }

  void changeLanguageReInitial() {
    if (audioService.isPlaying.value) {
      audioService.pauseRecorder();
    }

    audioService.reInitWs();
    audioService.connectedWsAndRecorder('wss://${NetWorkManager.WS_IP+NetWorkManager.SPEECH_RECOGNITION}?channel=azure&transStrategy=2',
        DataCallBack(
            confirmCallBack: (v) {
              audioService.record();
            }
        ));
  }

  void chooseFromLanguages(setState) async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
    'code': audioService.fromLanguage
    });
    audioService.fromLanguage = languageItem['code'];
    audioService.fromLanFlagDisplay.value = languageItem['desc'];

  }

  void chooseToLanguages(setState) async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
      'code': audioService.toLanguage
    });
    audioService.toLanguage = languageItem['code'];
    audioService.toLanFlagDisplay.value = languageItem['desc'];

  }


}
